package router

import (
	"encoding/base64"
	"encoding/json"
	"strings"

	"jgt-wallet/src/schema"
	"jgt-wallet/src/util"

	"github.com/teambition/gear"
)

// DefaultUserMiddleware 默认用户中间件
func DefaultUserMiddleware(ctx *gear.Context) error {
	ctx.SetAny(util.GetUserIDKey(), "5b6bf2361d41c845270ecf5e")
	ctx.SetAny(util.GetUserTypeKey(), "99")
	return nil
}

// TraceIDMiddleware 跟踪ID中间件
func TraceIDMiddleware(prefixes ...string) gear.Middleware {
	return func(ctx *gear.Context) error {
		allow := false
		for _, r := range prefixes {
			if strings.HasPrefix(ctx.Path, r) {
				allow = true
				break
			}
		}
		if !allow {
			return nil
		}

		traceID := ctx.GetHeader("X-Request-Id")
		if traceID == "" {
			traceID = util.UUID()
		}
		ctx.SetAny(util.GetTraceIDKey(), traceID)
		return nil
	}
}

// APPParameterMiddleware 收集APP信息
func APPParameterMiddleware() gear.Middleware {
	return func(ctx *gear.Context) error {
		appParameter := ctx.GetHeader("X-JGT-APP")
		if appParameter == "" {
			return nil
		}

		buf, err := base64.URLEncoding.DecodeString(appParameter)
		if err == nil && len(buf) > 0 {
			item := new(schema.AppParameter)
			json.Unmarshal(buf, item)
			ctx.SetAny(util.GetAPPParameterKey(), item)
		}

		return nil
	}
}
